<script setup>
import { ref, watch } from 'vue'
import { formatDate } from '@/utils/format'
import { getSingerList, delSinger } from '@/api/singer'
import SingerDetail from './subs/SingerDetail.vue'
import EditSinger from './subs/EditSinger.vue'
import { baseURL } from '@/api/request'

// 显示图片
const getFullImageUrl = (picPath) => {
  return baseURL + '/r' + picPath
}

const singers = ref([])
const searchQuery = ref('') // 独立的搜索查询ref
const queryParams = ref({
  pageNo: 1,
  size: 5,
  search: ''
})
const total = ref(0)

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function() {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

const singerList = async () => {
  const { data } = await getSingerList(queryParams.value)  
  singers.value = data.records
  total.value = data.total
}

// 初始化加载
singerList()

// 分页
const change = (pageNo, size) => {
  queryParams.value.pageNo = pageNo
  queryParams.value.size = size
  singerList()
}

// 实时搜索函数（带防抖）
const realTimeSearch = debounce(() => {
  queryParams.value.search = searchQuery.value
  queryParams.value.pageNo = 1 // 搜索时重置到第一页
  singerList()
}, 500)

// 显式搜索函数
const submitForm = () => {
  queryParams.value.search = searchQuery.value
  queryParams.value.pageNo = 1
  singerList()
}

// 监听搜索查询变化
watch(searchQuery, () => {
  realTimeSearch()
})

const singerDetail = ref(null)
// 显示抽屉
const showDetail = (row) => {
  singerDetail.value.openDrawer(row)
}

const editSinger = ref(null)
const addSinger = () => {
  editSinger.value.openDrawer()
}

// 编辑
const editSinger1 = async row => { 
  editSinger.value.openDrawer(row.id)
}

// 删除
const deleteSinger = async row => { 
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => { 
    delSinger(row.id).then(res => {
      ElMessage.success(res.msg)
      singerList()
    }).catch(err => {
      console.error(err)
    })
  })
}
</script>

<template>
  <el-card style="max-width: 100%">
    <template #header>
      <div class="card-header">
        <el-form :inline="true" :model="queryParams" label-width="auto" class="demo-form-inline">
          <el-form-item label="歌手名">
            <el-input 
              placeholder="请输入歌手信息" 
              clearable 
              v-model="searchQuery" 
              @input="realTimeSearch" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="addSinger">添加</el-button>
      </div>
    </template>
    <el-table 
      :data="singers" 
      style="width: 100%"
      @row-click="showDetail">
      <el-table-column prop="id" label="编号" />
      <el-table-column prop="name" label="歌手名" />
      <el-table-column label="歌手照片">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px; cursor: pointer; object-fit: cover;"
            fit="cover"
            :src="baseURL + '/r' + scope.row.pic"
            :preview-src-list="[getFullImageUrl(scope.row.pic)]"
            hide-on-click-modal
            preview-teleported
            @click.stop
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="birth" label="歌手生日" :formatter="formatDate" />
      <el-table-column prop="introduction" label="个人介绍"
        :formatter="(row) => row.introduction?.slice(0, 20) + (row.introduction?.length > 20 ? '...' : '')">
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click.stop="editSinger1(row)">编辑</el-button>
          <el-button type="danger" @click.stop="deleteSinger(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="example-pagination-block">
      <el-pagination 
        background 
        layout="prev, pager, next" 
        @change="change" 
        :total="total"
        :page-size="queryParams.size" />
    </div>
  </el-card>
  <singer-detail ref="singerDetail" />
  <edit-singer ref="editSinger" @singer-list="singerList" />
</template>

<style scoped>
.el-card {
  min-height: 100%;
  width: 100vw;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>